// TestTTSDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TestTTS.h"
#include "TestTTSDlg.h"
#include "DlgProxy.h"
#include "Word2Txt.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define TEXT_SEP_SIGN ":"

/////////////////////////////////////////////////////////////////////////////
// CTestTTSDlg dialog

IMPLEMENT_DYNAMIC(CTestTTSDlg, CDialog);

CTestTTSDlg::CTestTTSDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTestTTSDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTestTTSDlg)
	m_strWord = _T("");
	m_strName = _T("");
	m_strFile = _T("");
	m_bChkHide = FALSE;
	m_bChkMute = FALSE;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_pAutoProxy = NULL;

	m_eStatus = EStatusEnd;
	m_nCurReadIdx = 0;
}

CTestTTSDlg::~CTestTTSDlg()
{
	// If there is an automation proxy for this dialog, set
	//  its back pointer to this dialog to NULL, so it knows
	//  the dialog has been deleted.
	if (m_pAutoProxy != NULL)
		m_pAutoProxy->m_pDialog = NULL;
}

void CTestTTSDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTestTTSDlg)
	DDX_Control(pDX, IDC_COMBO_RATE, m_cbRate);
	DDX_Control(pDX, IDC_COMBO_VOICE1, m_cbVoice);
	DDX_Control(pDX, IDC_LIST_ACTOR, m_listAt);
	DDX_Text(pDX, IDC_EDIT_WORD, m_strWord);
	DDX_Text(pDX, IDC_EDIT_NAME1, m_strName);
	DDX_Text(pDX, IDC_EDIT_FILE, m_strFile);
	DDX_Check(pDX, IDC_CHECK_HIDE, m_bChkHide);
	DDX_Check(pDX, IDC_CHECK_MUTE, m_bChkMute);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTestTTSDlg, CDialog)
	//{{AFX_MSG_MAP(CTestTTSDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_BUTTON_TEST, OnButtonTest)
	ON_BN_CLICKED(IDC_BUTTON_START, OnButtonStart)
	ON_BN_CLICKED(IDC_BUTTON_PAUSE, OnButtonPause)
	ON_BN_CLICKED(IDC_BUTTON_STOP, OnButtonStop)
	ON_NOTIFY(NM_CLICK, IDC_LIST_ACTOR, OnClickListActor)
	ON_CBN_SELCHANGE(IDC_COMBO_VOICE1, OnSelchangeComboVoice)
	ON_BN_CLICKED(IDC_CHECK_HIDE, OnCheckHide)
	ON_BN_CLICKED(IDC_CHECK_MUTE, OnCheckMute)
	ON_BN_CLICKED(IDC_BUTTON_BROWS, OnButtonBrows)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTestTTSDlg message handlers
CString GetCurWorkPath()
{
	char path_buffer[_MAX_PATH];
	char drive[_MAX_DRIVE];
	char dir[_MAX_DIR];
	char fname[_MAX_FNAME];
	char ext[_MAX_EXT];

	GetModuleFileName(NULL, path_buffer, _MAX_PATH);
	_splitpath(path_buffer, drive, dir, fname, ext);
	CString strDir;
	strDir += drive;
	strDir += dir;
	return strDir;
}

BOOL CTestTTSDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	m_listAt.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
	m_listAt.InsertColumn(ITEM_NAME_IDX, _T("Name"), LVCFMT_LEFT, 250);
	m_listAt.InsertColumn(ITEM_VOICE_IDX, _T("Voice"), LVCFMT_LEFT, 250);
	m_listAt.InsertColumn(ITEM_MUTE_IDX, _T("Mute"), LVCFMT_LEFT, 60);
	m_listAt.InsertColumn(ITEM_HIDE_IDX, _T("Hide"), LVCFMT_LEFT, 60);
	 
	m_strCurPath = GetCurWorkPath();
	m_strTmpFile = m_strCurPath + "tmp.txt";

	CLSIDFromProgID(L"SAPI.SpVoice", &m_CLSID_SpVoice);
	InitVoice();
	InitCbVoice();

	int nRate[] = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5};
	int nCenterPos = 0;
	for(int i = 0; i < sizeof(nRate)/ sizeof(int); i++)
	{
		CString str;
		str.Format("%d", nRate[i]);
		m_cbRate.AddString(str);
		if(nRate[i] == 0)
		{
			nCenterPos = i;
		}
	}
	m_cbRate.SetCurSel(nCenterPos);

//	m_strFile = m_strCurPath + "12th test.doc";
//	CWord2Txt::Save2Txt(m_strFile, m_strTmpFile);
//	InitWordsFromFile();
//	InitNameList();
//	InitEditShow();

	UpdateData(FALSE);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CTestTTSDlg::InitVoice()
{
	m_Voice.CreateDispatch(m_CLSID_SpVoice); 
	m_pDisp = m_Voice.m_lpDispatch; 

	HRESULT hr = m_pDisp->QueryInterface(m_CLSID_SpVoice, (void**)&m_Voice.m_lpDispatch); 
	if (hr == S_OK)
	{ 
		m_pDisp->Release();
		AfxMessageBox("Create voice fail, please check you system. Make sure of installing MSTTS.EXE and SPCHAPI.EXE");
		return;
	} 
	else 
	{ 
		m_Voice.AttachDispatch(m_pDisp, TRUE);
		m_Voice.Speak("", 2);
	}	
}

void CTestTTSDlg::InitCbVoice()
{
	m_VoiceList = m_Voice.GetVoices(NULL,NULL);
	int voiceCount = m_VoiceList.GetCount();
	for(int i = 0; i < voiceCount; i++)
	{
		ISpeechObjectToken object = m_VoiceList.Item(i);
		m_cbVoice.AddString(object.GetDescription(NULL));
	}
	m_Voice.SetRefVoice(m_VoiceList.Item(0));

	if(voiceCount > 0)
	{
		m_cbVoice.SetCurSel(0);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CTestTTSDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTestTTSDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

// Automation servers should not exit when a user closes the UI
//  if a controller still holds on to one of its objects.  These
//  message handlers make sure that if the proxy is still in use,
//  then the UI is hidden but the dialog remains around if it
//  is dismissed.

void CTestTTSDlg::OnClose() 
{
	OnButtonPause();
	if (CanExit())
		CDialog::OnClose();
}

void CTestTTSDlg::OnOK() 
{
	return;
	if (CanExit())
		CDialog::OnOK();
}

void CTestTTSDlg::OnCancel() 
{
	if (CanExit())
		CDialog::OnCancel();
}

BOOL CTestTTSDlg::CanExit()
{
	// If the proxy object is still around, then the automation
	//  controller is still holding on to this application.  Leave
	//  the dialog around, but hide its UI.
	if (m_pAutoProxy != NULL)
	{
		ShowWindow(SW_HIDE);
		return FALSE;
	}

	return TRUE;
}

void CTestTTSDlg::OnButtonTest() 
{
	// TODO: Add your control notification handler code here
//	InitWordsFromFile();
	m_strWord = "";
	int n = m_vWord.size();
	int m = m_vName.size();
	for(int i = 0; i < m_vWord.size(); i++)
	{
		m_strWord += m_vName[i];
		m_strWord += ":\r\n";
		m_strWord += m_vWord[i];
		m_strWord += "\r\n\r\n";
	}
	UpdateData(FALSE);

//	m_Voice.Speak("i'm a cat", 0);   // asynchronous call to Speak method of ISpeechVoice interface
}

CString FullFillAk(int nLen)
{
	CString str;
	for(int i = 0; i < nLen; i++)
	{
		str += '*';
	}
	return str;
}

void CTestTTSDlg::InitEditShow()
{
	m_strWord = "";
	for(int i = 0; i < m_vWord.size(); i++)
	{
		m_strWord += m_vName[i];
		m_strWord += ":\r\n";
		m_strWord += GetNameListItem(m_vName[i], ITEM_HIDE_IDX) == "" ? 
			m_vWord[i] : FullFillAk(m_vWord[i].GetLength());
		m_strWord += "\r\n\r\n";
	}
	UpdateData(FALSE);
	UpdatePos();
}

CString CTestTTSDlg::GetNameListItem(const CString &strName, int nIdx)
{
	for(int i = 0; i < m_listAt.GetItemCount(); i++)
	{
		if(m_listAt.GetItemText(i, ITEM_NAME_IDX) == strName)
		{
			return m_listAt.GetItemText(i, nIdx);
		}
	}
	return "";
}

void CTestTTSDlg::InitNameList()
{
	vector<CString> vIdName;
	for(int i = 0; i < m_vWord.size(); i++)
	{
		bool bFind = false;
		for(int j = 0; j < vIdName.size(); j++)
		{
			if(vIdName[j] == m_vName[i])
			{
				bFind = true;
				break;
			}
		}
		if(!bFind)
		{
			vIdName.push_back(m_vName[i]);
		}
	}
	m_listAt.DeleteAllItems();
	CString strVoice;
	if(m_cbVoice.GetCount() != 0)
	{
		m_cbVoice.GetLBText(0, strVoice);
	}
	for(i = 0; i < vIdName.size(); i++)
	{
		m_listAt.InsertItem(i, vIdName[i]);
		m_listAt.SetItemText(i, ITEM_VOICE_IDX, strVoice);
	}
}

void CTestTTSDlg::InitWordsFromFile(const char* szFileName)
{
	FILE *pf;
	pf = fopen(szFileName, "r");
	if(pf == NULL)
	{
		AfxMessageBox("Fail to " + m_strTmpFile);
		return;
	}

	m_vWord.clear();
	m_vName.clear();
	char buf[MAX_BUF_LEN] = {0};
	bool bHasGotName = false;
	int nCount = 0;
	char* pos = buf;
	while(fread(pos, 1, 1, pf) != NULL)
	{
		if(*pos != 0x0D && *pos != 0x0A)
		{
			pos++;
			continue;
		}
		else
		{
			*(pos+1) = 0;
			pos = buf;
		}
		CString strTmp = buf;
		TrimWord(strTmp);
		if(strTmp.GetLength() != 0)
		{
			if(bHasGotName)
			{
				m_vWord[nCount-1] += strTmp;
			}
			else
			{
				bHasGotName = true;
				strTmp.Replace(TEXT_SEP_SIGN, "");
				strTmp.MakeUpper();
				m_vName.push_back(strTmp);
				m_vWord.push_back("");
				nCount++;
			}			
		}
		else
		{
			bHasGotName = false;
		}
	}
	fclose(pf);
}

int SendThread(LPVOID pParam)
{
	CTestTTSDlg *pDlg = (CTestTTSDlg*)pParam;

	int nWaitTime = 50;
	int nTime = nWaitTime;
	while(!pDlg->IsThreadEnd())
	{
		Sleep(10);
		if(pDlg->IsThreadPause())
		{
			continue;
		}
		if(nTime++ < nWaitTime)
		{
			continue;
		}
		else
		{
			pDlg->Read();
			nTime = 0;
		}
	}

	return 0;
}

void CTestTTSDlg::TextFocusToPos()
{
	CEdit *pEd = (CEdit*)GetDlgItem(IDC_EDIT_WORD);
	int nStart,nEnd;
	pEd->GetSel(nStart, nEnd);
	int nCurLine = pEd->LineFromChar();
	CString strLine;
	while(nCurLine > 0)
	{
		char buf[1024] = {0};
		pEd->GetLine(nCurLine, buf, 1024);
		strLine = buf;
		TrimWord(strLine);
		if(strLine.GetLength() == 0)
		{
			nStart = pEd->LineIndex(nCurLine);
			break;
		}
		else
		{
			nCurLine--;
		}
	}
	if(nCurLine == 0)
	{
		nStart = 0;
	}

	m_nCurReadIdx = 0;
	m_nCurPos = m_nEndPos = 0;
	while(m_nEndPos < nStart)
	{
		PosMove();
		m_nCurReadIdx++;
	}
}

void CTestTTSDlg::OnButtonStart() 
{
	// TODO: Add your control notification handler code here
	OnButtonStop();
	Sleep(100);//wait for thread end

//	InitVoice();

	SetStatus(EStatusStart);
//	m_nCurReadIdx = 0;
//	m_nCurPos = m_nEndPos = 0;
	TextFocusToPos();
	AfxBeginThread( (AFX_THREADPROC)SendThread, this);
}

void CTestTTSDlg::OnButtonPause() 
{
	// TODO: Add your control notification handler code here
	if(GetStatus() != EStatusPause)
	{
		SetStatus(EStatusPause);
		m_Voice.Pause();		
	}
	else
	{
		m_Voice.Resume();
		SetStatus(EStatusStart);
	}
}

void CTestTTSDlg::OnButtonStop() 
{
	// TODO: Add your control notification handler code here
	m_Voice.Speak("", 0);//.ReleaseDispatch();//
	SetStatus(EStatusEnd);
}

void CTestTTSDlg::UpdatePos()
{
	CEdit *pEd = (CEdit*)GetDlgItem(IDC_EDIT_WORD);
	pEd->SetSel(m_nCurPos, m_nCurPos);
	pEd->SetSel(m_nCurPos, pEd->LineIndex(pEd->LineFromChar(m_nEndPos) + 6));
	pEd->SetSel(m_nCurPos, m_nEndPos);
}

void CTestTTSDlg::PosMove()
{
	CEdit *pEd = (CEdit*)GetDlgItem(IDC_EDIT_WORD);
	m_nCurPos = m_nEndPos;
	m_nEndPos = m_strWord.Find("\r\n\r\n", m_nCurPos);
	m_nEndPos += 4;
}

void CTestTTSDlg::Read()
{
	TRACE("%d\n",m_nCurReadIdx);
	if(m_nCurReadIdx >= m_vWord.size())
	{
		OnButtonStop();
		return;
	}
	
	CString strTrue = m_vWord[m_nCurReadIdx];

	PosMove();
	UpdatePos();

	if(GetNameListItem(m_vName[m_nCurReadIdx], ITEM_MUTE_IDX) == "")
	{
		m_Voice.SetVolume(100);
	}
	else
	{
		m_Voice.SetVolume(0);
	}

	CString strRate;
	m_cbRate.GetLBText(m_cbRate.GetCurSel(), strRate);
	m_Voice.SetRate(atoi(strRate));

	m_Voice.SetRefVoice(m_VoiceList.Item(
		GetCbVoiceIdx(GetNameListItem(m_vName[m_nCurReadIdx], ITEM_VOICE_IDX)) ));

	m_Voice.Speak(strTrue, 0);
	m_nCurReadIdx++;

	
}

void CTestTTSDlg::TrimWord(CString &strWord)
{
	strWord.TrimLeft();
	strWord.TrimRight();
}

CString CTestTTSDlg::GetTrueWord(const CString &strWord)
{
	CString strTrue;
	if(strWord.Find(TEXT_SEP_SIGN) != -1)
	{
		strTrue = strWord.Mid(strWord.Find(TEXT_SEP_SIGN) + 1);
	}
	TrimWord(strTrue);
	return strTrue;
}

int CTestTTSDlg::GetCbVoiceIdx(const CString &strVoice)
{
	for(int i = 0; i < m_cbVoice.GetCount(); i++)
	{
		CString str;
		m_cbVoice.GetLBText(i, str);
		if(str == strVoice)
		{
			return i;
		}
	}
	return -1;
}

void CTestTTSDlg::OnClickListActor(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	NM_LISTVIEW* pListView = (NM_LISTVIEW*)pNMHDR;
	int nIdx = pListView->iItem;
	if(nIdx != -1)
	{
		int col = 0;
		m_strName = m_listAt.GetItemText(nIdx, col++);
		CString strVoice = m_listAt.GetItemText(nIdx, col++);
		m_cbVoice.SetCurSel(GetCbVoiceIdx(strVoice));
		
		m_bChkMute = m_listAt.GetItemText(nIdx, col++) != "";
		m_bChkHide = m_listAt.GetItemText(nIdx, col++) != "";
		
		UpdateData(FALSE);
		UpdatePos();
	}

	m_cbVoice.SetFocus();
	
	*pResult = 0;
}

int CTestTTSDlg::GetCurSelListItem()
{
	POSITION pos = m_listAt.GetFirstSelectedItemPosition();
	int nItem = -1;
	while (pos)
	{
		nItem = m_listAt.GetNextSelectedItem(pos);
	}
	return nItem;
}

void CTestTTSDlg::OnSelchangeComboVoice() 
{
	// TODO: Add your control notification handler code here
	if(GetCurSelListItem() == -1)
	{
		return;
	}
	CString strVoice;
	m_cbVoice.GetLBText(m_cbVoice.GetCurSel(), strVoice);
	m_listAt.SetItemText(GetCurSelListItem(), ITEM_VOICE_IDX, strVoice);
}

void CTestTTSDlg::OnCheckHide() 
{
	// TODO: Add your control notification handler code here
	if(GetCurSelListItem() == -1)
	{
		return;
	}
	UpdateData();
	CString str = m_bChkHide ? "HIDE" : "";
	m_listAt.SetItemText(GetCurSelListItem(), ITEM_HIDE_IDX, str);
	InitEditShow();
}

void CTestTTSDlg::OnCheckMute() 
{
	// TODO: Add your control notification handler code here
	if(GetCurSelListItem() == -1)
	{
		return;
	}
	UpdateData();
	CString str = m_bChkMute ? "MUTE" : "";
	m_listAt.SetItemText(GetCurSelListItem(), ITEM_MUTE_IDX, str);
}

void CTestTTSDlg::OnButtonBrows() 
{
	// TODO: Add your control notification handler code here
	OnButtonStop();
	CFileDialog mFileDlg(TRUE, NULL,NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT
		,"docs(*.doc; *.docx; *.txt)|*.doc;*.docx;*.txt|", AfxGetMainWnd());
	bool bIsTxt = false;
	if(mFileDlg.DoModal() == IDOK)
	{
		m_strFile = mFileDlg.GetPathName();
		
		CString strExt;
		strExt = mFileDlg.GetFileExt();
		strExt.MakeUpper();
		bIsTxt = strExt == "TXT";
		UpdateData(FALSE);
	}
	else
	{
		return;
	}
	if(bIsTxt || CWord2Txt::Save2Txt(m_strFile, m_strTmpFile))
	{
		InitWordsFromFile(bIsTxt ? m_strFile : m_strTmpFile);
		::DeleteFile(m_strTmpFile);
		m_nCurReadIdx = 0;
		m_nCurPos = m_nEndPos = 0;
		InitNameList();
		InitEditShow();
	}
//	OnButtonStart();
}
